package com.lujieni.springbootcaffeine.service;

import com.lujieni.springbootcaffeine.cache.DefaultTTLCaffeineCache;
import com.lujieni.springbootcaffeine.dao.StudentDao;
import com.lujieni.springbootcaffeine.po.StudentPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class StudentCache extends DefaultTTLCaffeineCache<StudentPO> {

    @Autowired
    private StudentCaffeineCacheProvider studentCaffeineCacheProvider;

    @Autowired
    private StudentDao studentDao;

    /**
     * 缓存预热
     * @param
     */
    @Override
    public void warmData() {
        cache.invalidateAll();
        Map<String, StudentPO> data = studentDao.selectAll().stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
        cache.putAll(data);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        TimeUnit.SECONDS.sleep(60);
        setCacheProvider(studentCaffeineCacheProvider);
        setTimeOut(30 * 60);
        super.afterPropertiesSet();
        //warmData();
    }

}
